import { ofetch, type FetchOptions } from 'ofetch';
import type { ApiResponse } from '../libs/apiResponse';

export const rawFetch = ofetch.create({
  baseURL: '/',
  timeout: 30000,

  // 请求拦截器
  onRequest({ request, options }) {},

  // 请求错误处理
  onRequestError({ request, options, error }) {
    console.error('Request Error:', error);
  },

  // 响应拦截器
  onResponse({ request, response, options }) {
    console.log('Response:', response.status, response.statusText);
  },

  // 响应错误处理
  onResponseError({ request, response, options }) {
    console.error('Response Error:', response.status, response.statusText);

    // 统一错误处理
    switch (response.status) {
      case 401:
        // 未认证，清除token并跳转登录
        localStorage.removeItem('token');
        window.location.href = '/login';
        break;
      case 403:
        // 无权限
        console.error('Access denied');
        break;
      case 404:
        console.error('Resource not found');
        break;
      case 500:
        console.error('Server error');
        break;
      default:
        console.error('Unknown error:', response.status);
    }
  },

  // 重试配置
  retry: 1,
  retryDelay: 1000,
});

// 创建带类型的请求方法
export const clientFetch = {
  get: <T = any>(url: string, options?: FetchOptions<'json', any>) =>
    rawFetch<ApiResponse<T>>(url, { method: 'GET', ...options }),

  post: <T = any>(
    url: string,
    data?: any,
    options?: FetchOptions<'json', any>
  ) =>
    rawFetch<ApiResponse<T>>(url, {
      method: 'POST',
      body: data,
      ...options,
    }),

  put: <T = any>(
    url: string,
    data?: any,
    options?: FetchOptions<'json', any>
  ) =>
    rawFetch<ApiResponse<T>>(url, {
      method: 'PUT',
      body: data,
      ...options,
    }),

  delete: <T = any>(url: string, options?: FetchOptions<'json', any>) =>
    rawFetch<ApiResponse<T>>(url, { method: 'DELETE', ...options }),

  patch: <T = any>(
    url: string,
    data?: any,
    options?: FetchOptions<'json', any>
  ) =>
    rawFetch<ApiResponse<T>>(url, {
      method: 'PATCH',
      body: data,
      ...options,
    }),
};